import React, { useState, useEffect } from "react";
import { Layout, Menu } from "antd";
import { useNavigate, useLocation } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { selectMenuList, setCurrentMenu } from "../../store/reducers/tab";
import MenuConfig from "../../config";
import { generatePaths, generateRoutes } from '../utils'

const { Sider } = Layout;

const CommonAside = ({ collapsed }) => {
  const [items, setItems] = useState([]);
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const currentMenu = useSelector((state) => state.tab.currentMenu);
  
  const location = useLocation();
  const defaultOpenKeys = generatePaths(location.pathname)

  useEffect(() => {
    const itemData = generateRoutes(MenuConfig);
    setItems(itemData);
  }, []);

  const findPath = (items = [], path) => {
    let result = null;
    items.forEach((item) => {
      if (item.key === path) {
        result = item.label;
      } else if (item.children && item.children.length > 0) {
        const foundInChildren = findPath(item.children, path);
        if (foundInChildren) {
          result = foundInChildren;
        }
      }
    });
    return result;
  };

  const selectMenus = (e) => {
    navigate(e.key, { replace: true });
    const label = findPath(items, e.key);
    dispatch(
      selectMenuList({
        path: e.key,
        label,
      })
    );
    dispatch(setCurrentMenu(e.key));
  };

  return (
    <Sider trigger={null} collapsible collapsed={collapsed}>
      <h3 className="app-name">{collapsed ? "后台" : "通用后台管理系统"}</h3>
      <Menu
        theme="dark"
        mode="inline"
        defaultSelectedKeys={[currentMenu]}
        defaultOpenKeys={defaultOpenKeys}
        selectedKeys={[location.pathname]}
        items={items}
        onClick={selectMenus}
        style={{
          height: "100%",
        }}
      />
    </Sider>
  );
};

export default CommonAside;
